package me.zhengjie.poemQuestions.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.poemQuestions.domain.PoemQuestions;
import me.zhengjie.poemQuestions.domain.UserAnswerRecord;
import me.zhengjie.poemQuestions.domain.enums.QuestionType;
import me.zhengjie.poemQuestions.domain.vo.UserAnswerRecordQueryCriteria;
import me.zhengjie.poemQuestions.mapper.PoemQuestionsMapper;
import me.zhengjie.poemQuestions.mapper.UserAnswerRecordMapper;
import me.zhengjie.poemQuestions.service.UserAnswerRecordService;
import me.zhengjie.utils.PageResult;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.webuser.mapper.WebUsersMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class UserAnswerRecordServiceImpl extends ServiceImpl<UserAnswerRecordMapper, UserAnswerRecord>
        implements UserAnswerRecordService {

    private final PoemQuestionsMapper poemQuestionsMapper;

    private final UserAnswerRecordMapper userAnswerRecordMapper;

    private final WebUsersMapper webUsersMapper;


    @Override
    public PageResult<UserAnswerRecord> queryAll(UserAnswerRecordQueryCriteria criteria, Page<Object> page) {
        return PageUtil.toPage(userAnswerRecordMapper.findAll(criteria, page));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String checkAndSaveAnswer(UserAnswerRecord record) {
        // 1. 获取题目信息
        PoemQuestions question = poemQuestionsMapper.selectById(record.getQuestionId());
        if (question == null) {
            throw new RuntimeException("题目不存在！");
        }

        // 2. 重复作答校验
        QueryWrapper<UserAnswerRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", record.getUserId())
                .eq("question_id", record.getQuestionId());
        if (this.getOne(wrapper) != null) {
            return "您已作答过该题目，不能重复答题。";
        }

        // 3. 提取前端答案（单选题取“B. XXX”中的“B”；填空题直接取全串）
        String raw = record.getUserAnswer() == null ? "" : record.getUserAnswer().trim();
        String userAnswerNormalized;
        if (question.getType() == QuestionType.SINGLE_CHOICE) {
            // 按“.”分割，或空格
            String[] parts = raw.split("\\.|\\s+");
            userAnswerNormalized = parts.length > 0 ? parts[0].toUpperCase() : "";
        } else {
            // 填空题，直接比较全文
            userAnswerNormalized = raw;
        }

        // 4. 判断是否正确
        String correct = question.getCorrectAnswer().trim();
        boolean isCorrect = correct.equalsIgnoreCase(userAnswerNormalized);
        record.setIsCorrect(isCorrect);
        // 将存入数据库的答案统一为解析后的值，或根据需求保留 raw
        record.setUserAnswer(raw);

        // 5. 积分计算（正确得分 = difficulty * 10）
        int earnedPoints = isCorrect && question.getDifficulty() != null
                ? question.getDifficulty() * 10
                : 0;
        record.setEarnedPoints(earnedPoints);
        record.setAnsweredAt(Timestamp.valueOf(LocalDateTime.now()));

        // 6. 保存记录
        this.save(record);

        // 7. 更新用户积分并返回提示
        if (isCorrect) {
            webUsersMapper.incrementScore(record.getUserId(), earnedPoints);
            return String.format("回答正确，积分 +%d", earnedPoints);
        } else {
            // 填空题显示全文答案，单选题显示选项字母
            String answerDisplay = question.getType() == QuestionType.SINGLE_CHOICE
                    ? correct
                    : question.getCorrectAnswer();
            return "回答错误，正确答案是：" + answerDisplay;
        }
    }


}
